<?php
/**
 * 省市区模型
 */

namespace app\official\model;


use app\common\model\BaseModel;
use custom\Err;
use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;

class Region extends BaseModel {

    /**
     * 根据名称查找城市
     * @param $name
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getCityname($name) {
        $data = db('region')
            ->where('name', 'like', '%' . $name . '%')
            ->where('rank', 2)
            ->field('name,city_code,x(location) as lng,Y(location) as lat')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['lng'] = empty($v['lng']) ? '' : (string)($v['lng']);
            $data[$k]['lat'] = empty($v['lat']) ? '' : (string)($v['lat']);
        }
        if (empty($data)) {
            Err::add('数据不存在');
            return false;
        }
        return $data;
    }

    /**
     * 首页定位省市结构
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function indexCity() {
        $map[] = ['rank', 'in', '1,2'];//省市
        $map[] = ['id', 'not in', [25179, 25183]];
        $column = ['name', 'city_code', 'id', 'pid', 'initials', 'x(location) as lng', 'Y(location) as lat'];
        $data = db('region')
            ->where($map)
            ->field($column)
            ->order(['rank' => 'desc', 'initials' => 'asc'])
            ->select();
        return self::treeFilter($data);
    }

    /**
     * 省
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function province() {
        $map[] = ['rank', '=', 1];//省
        $map[] = ['id', 'not in', [25179, 25183]];
        $data = db('region')
            ->where($map)
            ->field('id,name')
            ->order('initials', 'asc')
            ->select();
        return $data;
    }

    /**
     * 获取树
     * @param $data
     * @return array
     */
    public static function treeFilter($data) {
        $data = array_column($data, null, 'id');
        $tree = [];
        foreach ($data as &$val) {
            if (isset($data[$val['pid']])) {//市
                $data[$val['pid']]['children'][] = [
                    'value'    => $val['city_code'],
                    'label'    => $val['name'],
                    'children' => $val['children'] ?? [],
                    'lat'      => empty($val['lat']) ? '' : (string)$val['lat'],
                    'lng'      => empty($val['lng']) ? '' : (string)$val['lng'],
                ];
            } else {//省
                $arr = [
                    'value'    => $val['city_code'],
                    'label'    => $val['name'],
                    'children' => $val['children'] ?? [],
                ];
                $tree[$val['initials']]['label'] = $val['initials'];
                $tree[$val['initials']]['children'][] = $arr;
            }
        }
        return array_values($tree);
    }

    /**
     * 根据省id找下面的市
     * @param $id
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getCity($id) {
        $data = db('region')
            ->where('pid', $id)
            ->field('name,city_code,x(location) as lng,Y(location) as lat')
            ->order('initials', 'asc')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['lng'] = empty($v['lng']) ? '' : (string)$v['lng'];
            $data[$k]['lat'] = empty($v['lat']) ? '' : (string)$v['lat'];
        }
        return $data;
    }

    /**
     * 城市下面的区域
     * @param $city_code
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getArea($city_code) {
        return db('region')
            ->where('p_code', $city_code)
            ->where('rank', 3)
            ->order('weights asc')
            ->field('name,city_code')
            ->select();
    }

    /**
     * 地图找房-区域
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function areaHouse($params) {
        $region = Db::name('region')
            ->where('p_code', $params['city_code'])
            ->where('rank', 3)
            ->field('name,city_code,x(location) as lng,Y(location) as lat,house_number')
            ->select();
        foreach ($region as $k => $v) {
            //过滤没有经纬度的区域
            if ($region[$k]['lng'] == 0 || $region[$k]['lat'] == 0) {
                unset($region[$k]);
            } else {
                $region[$k]['lng'] = (string)$region[$k]['lng'];
                $region[$k]['lat'] = (string)$region[$k]['lat'];
            }
        }
        return array_merge($region);
    }

    /**
     * code转经纬度
     * @param $code
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function codeToLocation($code) {
        return db("region")
            ->where('city_code', $code)
            ->field('name,x(location) as lng,Y(location) as lat')
            ->find();
    }

    /**
     * 筛选多条
     * @param $map
     * @param $column
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getDatas($map, $column) {
        return db('region')
            ->where($map)
            ->field($column)
            ->select();
    }

    /**
     * 城市列表
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function cityList() {
        $cityList = config('global.house_city_open');
        $data = db('region')
            ->where('city_code', 'in', $cityList)
            ->field('city_code,name,x(location) as lng,Y(location) as lat')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['key'] = $v['city_code'];
            $data[$k]['val'] = $v['name'];
            $data[$k]['lng'] = empty($v['lng']) ? '' : $v['lng'];
            $data[$k]['lat'] = empty($v['lat']) ? '' : $v['lat'];
            unset($data[$k]['city_code']);
            unset($data[$k]['name']);
        }
        return $data;
    }
}
